<!--
 * @Author: [yuantongxin]
 * @Date: 2021-10-21 17:21:11
 * @LastEditors: [yuantongxin]
 * @LastEditTime: 2021-10-25 18:43:39
 * @Description: 
-->
<template>
  <div>
    <div style="padding: 20px">
      <!-- 按钮开始 -->
      <div>
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-button
            type="primary"
            size="small"
            style="margin-right: 15px"
            @click="toAdd"
            >添加</el-button
          >
          <el-form-item>
            <el-input
              v-model="form.name"
              placeholder="请输入名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="form.status" placeholder="请选择状态" clearable>
              <el-option label="正常" value="正常"></el-option>
              <el-option label="下架" value="下架"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="form.productCategoryId"
              placeholder="请选择栏目"
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in category"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 按钮结束 -->
      <!-- 表格开始 -->
      <div>
        <!-- {{tableData}} -->
        <el-table :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column type="index" :index="1" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="id" label="产品编号" width="160">
          </el-table-column>
          <el-table-column prop="name" label="名称" width="160">
          </el-table-column>
          <el-table-column prop="photo" label="图片" width="170">
            <template slot-scope="scope">
              <div>
                 <el-popover placement="right" trigger="hover">
                <el-image
                  slot="reference"
                  style="width: 30px; height: 30px"
                  :src="scope.row.photo"
                >
                </el-image>
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.photo"
                ></el-image>
              </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="160">
          </el-table-column>
          <el-table-column prop="status" label="状态" width="160">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.status==='正常'">正常</el-tag>
              <el-tag type="danger" v-else>下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="category.name" label="所属栏目" width="160">
          </el-table-column>

          <el-table-column label="操作" width="170">
            <template slot-scope="scope">
              <el-button @click="toEdit(scope.row)" type="text" icon="el-icon-edit" size="small">编辑</el-button>
              <el-button @click="toChangeStatus(scope.row.id,'上架')" type="text" style="color:#4075ab" size="small" v-if="scope.row.status==='下架'">上架</el-button>
              <el-button @click="toChangeStatus(scope.row.id,'下架')" type="text" style="color:#e76777"  size="small" v-else>下架</el-button>
              <!-- <el-button
                type="text"
                size="small"
                @click="toDelete(scope.row.id)"
                style="color: #e65f70"
                >下架</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 表格结束 -->
      <!-- 分页开始 -->
      <div style="text-align: right; margin: 5px">
        <el-pagination
        background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 分页结束 -->
      <!-- 模态框开始 -->
      <div>
        <el-dialog :title="title" :visible.sync="visible">
          <el-form :model="form" :rules="rules" ref="myForm">
            <el-form-item
              label="产品名称"
              :label-width="formLabelWidth"
              prop="name"
            >
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="所属栏目" :label-width="formLabelWidth">
              <el-select v-model="form.productCategoryId" placeholder="请选择产品栏目">
                <el-option :label="item.name" :value="item.id" v-for="item in category" :key='item.id'></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="价格"
              :label-width="formLabelWidth"
              prop="price"
            >
              <el-input v-model="form.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="封面"
              :label-width="formLabelWidth"
              prop="photo"
            >
              <el-upload
                class="avatar-uploader"
                :action="uploadFileURL"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="form.photo" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="产品描述" :label-width="formLabelWidth">
              <el-input
                v-model="form.description"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取 消</el-button>
            <el-button type="primary" @click="toSubmit('myForm')"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
      <!-- 模态框结束 -->
    </div>
  </div>
</template>

<script>
import { pageQuery as pageQueryPro } from "@/api/product";
import { saveOrUpdate, offline, online } from "@/api/product";
import { pageQuery } from "@/api/column";
import { showFileURL, uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      loading:true,
      rules: {
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
        photo: [{ required: true, message: "请上传栏目图标", trigger: "blur" }],
      },
      category: [],
      imageUrl: "",
      // 图片显示的基础路径
      showFileURL,
      // 文件上传的路径
      uploadFileURL,
      // 双向数据绑定
      form: {},
      // 表单控件的宽度
      formLabelWidth: "80px",
      // 表格绑定的数据
      tableData: [],
      // 模态框title变量
      title: "",
      // 控制模态框显示与隐藏
      visible: false,
      total: 0,
      params: {
        page: 1,
        pageSize: 10,
      },
      input: "",

      options: [
        {
          value: "选项1",
          label: "正常",
        },
        {
          value: "选项2",
          label: "下架",
        },
      ],
      value: "",
    };
  },
  watch: {
    params: {
      handler() {
        this.queryPage();
      },
      deep: true,
    },
  },
  created() {
    this.queryPage();
    this.categoryPro();
  },
  methods: {
    // 给搜索按钮绑定事件 == 模糊查询
    async toSearch() {
      let temp = {
        ...this.params,
        ...this.form,
      };
      for (let key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      let res = await pageQueryPro(temp);
      this.tableData = res.data.list;
      this.total = res.data.total;
      // console.log(res);
    },

    // async toDelete(id) {
    //   let res = await offline(id);
    //   this.queryPage();
    // },
      async toChangeStatus(id,type){
        let res = {}
        if(type==='上架'){
           res = await online({id})
        }else{
           res = await offline({id})
        }
        this.$message({
          type:'success',
          message:res.message
        })
        this.queryPage()
      },
     toSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await saveOrUpdate(this.form);
          this.visible = false;
          console.log(res);
          this.$message({
            message: res.message,
            type: "success"
          });
          // 刷新页面
          this.queryPage();
          // alert("submit!");
        } else {
          this.$message.error('保存失败');
          return false;
        }
      });
    },
    //
    toEdit(row) {
      this.visible = true;
      this.title = "修改产品信息";
      this.form = { ...row };
      this.imageUrl = this.form.photo;
    },
    // 给添加按钮绑定事件
    toAdd() {
      this.visible = true;
      this.title = "添加产品信息";
      this.form = {};
    },
    // 封装所有栏目
    async categoryPro() {
      let res = await pageQuery({
        page: 1,
        pageSize: 10,
      });
      this.category = res.data.list;
    },
    async queryPage() {
      let temp = {
        ...this.params,
      };
      let res = await pageQueryPro(temp);
      // console.log(res);

      this.tableData = res.data.list;
      this.total = res.data.total;
      this.loading = false
    },
    //  处理每页显示的条数
    handleSizeChange(pageSize) {
      //   console.log(`每页 ${pageSize} 条`);
      this.params.pageSize = pageSize;
      // this.queryPage()
    },
    // 处理当前页
    handleCurrentChange(page) {
      //   console.log(`当前页: ${page}`);
      this.params.page = page;
      // this.queryPage()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res);
      //
      this.form.photo = showFileURL + res.data.id;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scope>
</style>